<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;

class UserController extends Controller
{
    /**
     * 获取用户资料
     */
    public function profile(Request $request)
    {
        $user = $request->user();
        $user->load(['statistics', 'currentTier']);

        return $this->success([
            'id' => $user->id,
            'username' => $user->username,
            'email' => $user->email,
            'email_verified_at' => $user->email_verified_at,
            'avatar_url' => $user->avatar_url,
            'created_at' => $user->created_at,
            'statistics' => $user->statistics ? [
                'total_training_sessions' => $user->statistics->total_training_sessions,
                'successful_sessions' => $user->statistics->successful_sessions,
                'success_rate' => $user->statistics->success_rate,
                'consecutive_days' => $user->statistics->consecutive_days,
                'total_experience_points' => $user->statistics->total_experience_points,
                'last_training_date' => $user->statistics->last_training_date,
            ] : null,
            'current_tier' => $user->currentTier() ? [
                'tier_name' => $user->currentTier()->tier_name,
                'tier_level' => $user->currentTier()->tier_level,
                'experience_points' => $user->currentTier()->experience_points,
                'description' => $user->currentTier()->description,
                'next_tier' => $user->currentTier()->getNextTierInfo(),
            ] : null,
        ]);
    }

    /**
     * 更新用户资料
     */
    public function updateProfile(Request $request)
    {
        $user = $request->user();

        $validator = Validator::make($request->all(), [
            'username' => 'sometimes|string|min:3|max:50|unique:users,username,' . $user->id,
            'email' => 'sometimes|email|unique:users,email,' . $user->id,
        ]);

        if ($validator->fails()) {
            return $this->error('输入数据验证失败', 422, $validator->errors());
        }

        try {
            $updateData = [];

            if ($request->has('username')) {
                $updateData['username'] = $request->username;
            }

            if ($request->has('email')) {
                $updateData['email'] = $request->email;
                // 如果更改了邮箱，需要重新验证
                $updateData['email_verified_at'] = null;
            }

            if (!empty($updateData)) {
                $user->update($updateData);
            }

            return $this->success([
                'id' => $user->id,
                'username' => $user->username,
                'email' => $user->email,
                'email_verified_at' => $user->email_verified_at,
                'avatar_url' => $user->avatar_url,
            ], '资料更新成功');

        } catch (\Exception $e) {
            return $this->error('资料更新失败', 500);
        }
    }

    /**
     * 上传头像
     */
    public function uploadAvatar(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'avatar' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048', // 最大2MB
        ]);

        if ($validator->fails()) {
            return $this->error('头像文件验证失败', 422, $validator->errors());
        }

        try {
            $user = $request->user();
            $file = $request->file('avatar');

            // 生成文件名
            $filename = 'avatars/' . $user->id . '_' . time() . '.' . $file->getClientOriginalExtension();

            // 处理图片（压缩和裁剪）
            $image = Image::make($file);
            $image->fit(200, 200); // 裁剪为200x200像素
            $image->encode('jpg', 80); // 压缩质量80%

            // 保存到存储
            Storage::disk('public')->put($filename, $image->stream());

            // 删除旧头像
            if ($user->avatar_url) {
                $oldPath = str_replace('/storage/', '', $user->avatar_url);
                Storage::disk('public')->delete($oldPath);
            }

            // 更新用户头像URL
            $avatarUrl = '/storage/' . $filename;
            $user->update(['avatar_url' => $avatarUrl]);

            return $this->success([
                'avatar_url' => $avatarUrl
            ], '头像上传成功');

        } catch (\Exception $e) {
            return $this->error('头像上传失败', 500);
        }
    }

    /**
     * 修改密码
     */
    public function changePassword(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'current_password' => 'required|string',
            'new_password' => 'required|string|min:8|confirmed',
        ]);

        if ($validator->fails()) {
            return $this->error('输入数据验证失败', 422, $validator->errors());
        }

        $user = $request->user();

        // 验证当前密码
        if (!Hash::check($request->current_password, $user->password)) {
            return $this->error('当前密码不正确', 400);
        }

        try {
            $user->update([
                'password' => Hash::make($request->new_password)
            ]);

            return $this->success(null, '密码修改成功');

        } catch (\Exception $e) {
            return $this->error('密码修改失败', 500);
        }
    }

    /**
     * 获取用户统计数据
     */
    public function statistics(User $user, Request $request)
    {
        // 检查是否为当前用户或有权限查看
        if ($user->id !== $request->user()->id) {
            return $this->error('无权查看其他用户的统计数据', 403);
        }

        $user->load(['statistics', 'abilities', 'achievements', 'trainingSessions']);

        $latestAbility = $user->latestAbilities();
        $recentSessions = $user->trainingSessions()
                              ->where('created_at', '>=', now()->subDays(7))
                              ->get();

        return $this->success([
            'basic_stats' => [
                'total_training_sessions' => $user->statistics->total_training_sessions ?? 0,
                'successful_sessions' => $user->statistics->successful_sessions ?? 0,
                'success_rate' => $user->statistics->success_rate ?? 0,
                'consecutive_days' => $user->statistics->consecutive_days ?? 0,
                'total_experience_points' => $user->statistics->total_experience_points ?? 0,
            ],
            'ability_summary' => $latestAbility ? [
                'breaking_ice' => $latestAbility->breaking_ice,
                'empathy' => $latestAbility->empathy,
                'conversation_flow' => $latestAbility->conversation_flow,
                'total_score' => $latestAbility->getTotalScore(),
            ] : null,
            'recent_activity' => [
                'sessions_this_week' => $recentSessions->count(),
                'successful_this_week' => $recentSessions->where('success_achieved', true)->count(),
                'last_training_date' => $user->statistics->last_training_date ?? null,
            ],
            'achievements_count' => $user->achievements->count(),
            'tier_info' => $user->currentTier() ? [
                'tier_name' => $user->currentTier()->tier_name,
                'tier_level' => $user->currentTier()->tier_level,
            ] : null,
        ], '获取用户统计数据成功');
    }

    /**
     * 获取用户收藏的角色
     */
    public function favoriteCharacters(User $user, Request $request)
    {
        // 检查是否为当前用户或有权限查看
        if ($user->id !== $request->user()->id) {
            return $this->error('无权查看其他用户的收藏', 403);
        }

        $favoriteCharacters = $user->favoriteCharacters()
                                  ->where('is_active', true)
                                  ->get();

        $formattedCharacters = $favoriteCharacters->map(function ($character) {
            return [
                'id' => $character->id,
                'name' => $character->name,
                'personality_type' => $character->personality_type,
                'description' => $character->description,
                'difficulty_level' => $character->difficulty_level,
                'difficulty_text' => $character->difficulty_text,
                'avatar_url' => $character->avatar_url,
                'tags' => $character->tags_array,
                'favorited_at' => $character->pivot->created_at,
            ];
        });

        return $this->success($formattedCharacters, '获取收藏角色成功');
    }
}